<template>
  <div>
    <!-- 顶部面包屑标识与导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/sys-admin/product/spu-management'}">SPU台账</el-breadcrumb-item>
      <el-breadcrumb-item><span>{{ spu.name }}</span></el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <!-- 操作区域 -->
    <div style="margin: 0 0 20px 0;">
      <el-button type="primary" size="medium" @click="openAddNewDialog">新增SKU</el-button>
      <el-button type="warning" size="medium" @click="gotoList">返回列表</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="title" label="标题" header-align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="barCode" label="条形码" width="140" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="price" label="售价" width="80" align="center"></el-table-column>
      <el-table-column prop="stock" label="库存" width="80" align="center"></el-table-column>
      <el-table-column prop="stockThreshold" label="库存阈警值" width="100" align="center"></el-table-column>
      <el-table-column prop="sales" label="销量" width="80" align="center"></el-table-column>
      <el-table-column prop="positiveCommentCount" label="好评" width="80" align="center"></el-table-column>
      <el-table-column prop="commentCount" label="评论" width="80" align="center"></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="100" align="center"></el-table-column>
      <el-table-column label="参数清单" width="100" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="openParamListDialog(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle size="mini"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle size="mini"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 参数清单的对话框 -->
    <el-dialog class="sku-param-list" :title="skuInfo.title + ' 配置清单'" :visible.sync="paramListDialogVisible">
      <el-descriptions :column="1" border label-class-name="description-label">
        <el-descriptions-item v-for="param in skuInfo.params" :label="param.name">{{
            param.value
          }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 新增SKU表单的对话框 -->
    <el-dialog title="新增SKU" :visible.sync="addNewDialogVisible">
      <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <!-- SKU的固定属性 -->
        <el-form-item label="标题">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="条形码">
          <el-input v-model="ruleForm.barCode"></el-input>
        </el-form-item>
        <el-form-item label="售价">
          <el-input v-model="ruleForm.price">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <!-- 根据属性模板中的属性动态生成的控件 -->
        <el-form-item :label="attribute.name" v-for="attribute in attributeList" :key="attribute.id">
          <!-- 属性：输入框 -->
          <template v-if="attribute.inputType == INPUT_TYPE_TEXT">
            <el-input v-model="specificationObject[attribute.name]">
              <template v-if="attribute.unit" slot="append">{{ attribute.unit }}</template>
            </el-input>
          </template>
          <!-- 属性：单选按钮 -->
          <template v-else-if="attribute.inputType == INPUT_TYPE_CHECKBOX_SINGLE">
            <el-radio-group v-model="specificationObject[attribute.name]">
              <el-radio :label="attribute.unit ? value + attribute.unit : value"
                        v-for="value in attribute.valueList.split(',')">{{ value }}
                <span v-if="attribute.unit">{{ attribute.unit }}</span>
              </el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <!-- SKU的固定属性 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="库存">
              <el-input v-model="ruleForm.stock"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存阈警值">
              <el-input v-model="ruleForm.stockThreshold"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="排序序号">
          <el-input v-model="ruleForm.sort"></el-input>
        </el-form-item>
        <!-- 最下方的按钮栏 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 当前显示SKU列表的SPU数据
      spu: {
        id: 0,
        name: 'SPU名称'
      },
      // 表格数据
      tableData: [],
      // 需要显示清单的SKU
      skuInfo: {
        title: '',
        params: []
      },
      // 参数清单对话框的可见性
      paramListDialogVisible: false,
      // 属性列表
      attributeList: [
        {
          id: 0,
          name: '',
          description: '',
          type: 0,
          inputType: 0,
          valueList: '',
          unit: '',
          sort: 0,
          isAllowCustomize: 0
        }
      ],
      // 新增SKU对话框的可见性
      addNewDialogVisible: false,
      // 新增SKU对话框的表单的label宽度
      formLabelWidth: '120px',
      // 常量：控件类型
      INPUT_TYPE_TEXT: 0,
      INPUT_TYPE_CHECKBOX_SINGLE: 1,
      INPUT_TYPE_CHECKBOX_MULTI: 2,
      // 表单
      specificationObject: {},
      ruleForm: {
        spuId: '',
        title: 'Redmi Note 11 5G 流光紫 高配版 骁龙888 16GB 512GB',
        barCode: '10061767427568',
        price: '2999',
        stock: '1000',
        stockThreshold: '100',
        sort: '',
        specifications: ''
      },
    }
  },
  methods: {
    // 返回列表
    gotoList() {
      this.$router.push('./');
    },
    // 打开属性清单对话框
    openParamListDialog(sku) {
      this.skuInfo.title = sku.title;
      let params = JSON.parse(sku.specifications);
      this.skuInfo.params = Object.keys(params).map(key => ({
        name: key,
        value: params[key],
      }));
      this.paramListDialogVisible = true;
    },
    // 打开编辑对话框
    openEditDialog(sku) {
      let title = '提示';
      let message = '您正在尝试编辑【' + sku.id + '-' + sku.title + '】的SKU数据，抱歉，此功能尚未实现……';
      this.$alert(message, title, {
        confirmButtonText: '确定',
        callback: action => {
        }
      });
    },
    // 打开删除确认框
    openDeleteConfirm(sku) {
      let title = '提示';
      let message = '您正在尝试删除【' + sku.id + '-' + sku.title + '】的SKU数据，抱歉，此功能尚未实现……';
      this.$alert(message, title, {
        confirmButtonText: '确定',
        callback: action => {
        }
      });
    },
    // 打开新增SKU对话框
    openAddNewDialog() {
      this.ruleForm.spuId = this.spu.id;
      this.addNewDialogVisible = true;
    },
    // 提交表单
    submitForm(formName) {
      let url = 'http://localhost:9180/sku/add-new';
      console.log('url = ' + url);

      this.ruleForm.specifications = JSON.stringify(this.specificationObject);
      let formData = this.qs.stringify(this.ruleForm);
      console.log('formData = ' + formData);

      let localJwt = localStorage.getItem('localJwt');

      this.axios.create({
        'headers': {
          'Authorization': localJwt
        }
      }).post(url, formData).then((response) => {
        let jsonResult = response.data;
        console.log(jsonResult);
        if (jsonResult.state == 20000) {
          this.$message({
            showClose: true,
            message: '添加SKU成功！',
            type: 'success'
          });
          this.addNewDialogVisible = false;
          this.resetForm(formName);
          this.loadSkuList();
        } else {
          this.$message({
            showClose: true,
            message: jsonResult.message,
            type: 'error'
          });
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 加载SPU信息
    loadSpuInfo() {
      let spuId = parseInt(this.$router.currentRoute.query.spuId);
      if (!spuId || spuId < 1) {
        let message = '参数错误，无法加载SPU数据！';
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
            this.$router.push('/sys-admin/product/spu-management');
            return;
          }
        });
      }

      let url = 'http://localhost:9180/spu/' + spuId;
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt');

      this.axios.create({
        'headers': {
          'Authorization': localJwt
        }
      }).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.spu = jsonResult.data;
          this.loadSkuList();
          this.loadAttributeList();
        } else {
          this.$alert(jsonResult.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.$router.push('/sys-admin/product/spu-management');
            }
          });
        }
      });
    },
    // 加载SPU的属性列表
    loadAttributeList() {
      let url = 'http://localhost:9180/attributes/list-by-template?templateId=' + this.spu.attributeTemplateId;
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt');

      this.axios.create({
        'headers': {
          'Authorization': localJwt
        }
      }).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.attributeList = jsonResult.data.list;
        } else {
          this.$alert(jsonResult.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.$router.push('/sys-admin/product/spu-management');
            }
          });
        }
      });
    },
    // 加载SKU列表
    loadSkuList() {
      let url = 'http://localhost:9180/sku/list-by-spu?spuId=' + this.spu.id;
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt');

      this.axios.create({
        'headers': {
          'Authorization': localJwt
        }
      }).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
        }
      });
    }
  },
  mounted() {
    this.loadSpuInfo();
  }
}
</script>

<style>
.sku-param-list {
}

.sku-param-list .description-label {
  width: 150px;
}
</style>